<?php

namespace app\api\controller\yexam;

use app\admin\model\Taocan;
use app\admin\model\yexam\Third;
use app\api\model\CardsModel;
use app\api\model\OrderModel;
use app\api\model\UserSubjectModel;
use app\common\controller\Api;
use EasyWeChat\Factory;
use fast\Random;

/**
 * Ad接口
 */
class Order extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    // 判断是否可以直接观看

    public function checkPayStatus(){
        $subject_id = input('subject_id');
        $model = new UserSubjectModel();
        $data = $model
            ->where(['user_id'=>$this->auth->id,'subject_id'=>$subject_id])
            ->order('createtime','desc')
            ->find();
        if(empty($data)){
            $this->success('请购买后查看',['pay_status'=>0]);
        }
        if($data['createtime']+ $data['day'] * 60 * 60 * 24 < time()){
            $this->success('订单已失效，请重新购买',['pay_status'=>0]);
        }
        $this->success('',['pay_status'=>1]);
    }

    public function taocan(){
        $TaocanModel = new Taocan();
        $data = $TaocanModel->where(['status'=>1])->select();
        $this->success('',$data);
    }

    public function addorder(){
        $user_id = $this->auth->id;
        $input = input();
        $input['user_id'] = $user_id;
        $order_sn = 'DD'.date('YmdHis').Random::alnum(8);
        $input['order_sn'] =  $order_sn;

        $orderModel = new OrderModel();
        if($input['pay_type'] == 'card'){
            $card_sn = $input['card_sn'];
            $card_password = $input['card_password'];
            $cardModel = new CardsModel();
            $carddata = $cardModel::get(['card_num'=>$card_sn]);
            $input['day'] = $carddata['day'];
            $input['card_id'] = $carddata['id'];
            $id = OrderModel::addorder($input);
            if(empty($carddata)){
                $orderModel->where(['id'=>$id])->delete();
                $this->error('学习卡不存在',['response'=>0]);
            }
            if($carddata['card_password'] != md5(md5($card_password).$carddata['card_salt']) && $card_password != $carddata['card_password_yuan']){
                $orderModel->where(['id'=>$id])->delete();
                $this->error('密码输入错误',['response'=>0]);
            }
            if($carddata['status'] == 2 ){
                $orderModel->where(['id'=>$id])->delete();
                $this->error('学习卡已失效',['response'=>0]);
            }
            $orderModel->where(['id'=>$id])->update(['pay_status'=>2,'pay_time'=>time()]);
            $orderdata = $orderModel::get($id);
            $orderdata['card_id']=$carddata['id'];
            UserSubjectModel::addUserSub($orderdata);
            $this->success('购买成功',['response'=>1]);
        }else{
            $input['user_id']= $user_id;
            $id = OrderModel::addorder($input);
            $method = $input['method'];//小程序/h5
            $notify_url = $_SERVER['HTTP_HOST']."/addons/epay/api/notifyx/type/wechat";
            $return_url = $_SERVER['HTTP_HOST'];
            if($method == 'web'){
                $type = 'mp';
            }else{
                $type = 'mini';
            }
            $thirdModel = new Third();
            $thirduser = $thirdModel->where(['type'=>$type,'user_id'=>$this->auth->id])->find();
            if($thirduser){
                $openid = $thirduser['openid'];
            }else {
                $openid = $this->getopenid($input['code'],$type);
                if($openid == false){
                    $this->error('请微信授权后支付');
                }
            }
            $params = [
                //订单金额  如果是法务修改订单  有个参数new_money   其他都是订单id
                'amount' => $input['total'],
//            'amount' => 0.01,
                'orderid' => $order_sn,
                'type' => $input['pay_type'],
                'title' => "购买课程",
                'notifyurl' => $notify_url,
                'returnurl' => $return_url,
                'method' => $method,//web   miniapp
                'openid' => $openid,  //微信的jsapi支付 和 微信体现需要
                'auth_code' => ""
            ];
            $response = \addons\epay\library\Service::submitOrder($params);
            $response = json_decode($response);
            if($response){
                $this->success('预付订单',['response'=>$response]);
            }else{
                $orderModel->where(['id'=>$id])->delete();
                $this->error('支付失败',['response'=>0]);
            }
        }
    }

    public function getopenid($code,$type){
        $config = get_addon_config('yexam');
        if($type == 'mini'){
            $options = [
                'app_id'   => $config['mini']['app_id'],
                'secret'   => $config['mini']['app_secret'],
            ];

            $app = Factory::miniProgram($options);
            $sns = $app->auth->session($code);
            if(isset($sns['openid'])){
                return $sns['openid'];
            }else{
                return  false;
            }

        }else{
            $options = array(
                'token'   => "", //填写你设定的key
                'aes_key' => "", //填写加密用的EncodingAESKey
                'app_id'  => $config['mp']['app_id'], //填写高级调用功能的app id
                'secret'  => $config['mp']['app_secret'] //填写高级调用功能的密钥
            );

            $app = Factory::officialAccount($options);
            $oauth = $app->oauth;

            $user = $oauth->user();
            if(isset($user['original']['openid'])){
                return $user['original']['openid'];
            }else{
                return  false;
            }
        }
    }


}
